#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from dws.resource.dws_database import DwsDatabase
from dws.resource.dws_schema import DwsSchemaParam, DwsSchema
from dws.resource.dws_table import DwsTableParam, DwsTable


class QueryRes():
    def __init__(self, usr, env_path):
        self._usr = usr
        self._env_path = env_path

    def query_all_database_in_cluster(self):
        """
        @函数说明：查询集群中的database

        """
        return DwsDatabase(self._usr, self._env_path).get_all_databases().split(',')

    def query_schema_in_database(self, database_name, page_no, page_size=100):
        """
        @函数说明：查询某个schema中的表
        返回值 schema_list 不包含 database 前缀
        """
        schemas = DwsSchema(DwsSchemaParam(user_name=self._usr, env_file=self._env_path, db_name=database_name,
                                           condition={"pageNo": page_no, "pageSize": page_size})).get_all_schemas()

        ret_schemas = []
        for schema in schemas:
            ret_schemas.append(schema.get('name').split('/').pop())

        return ret_schemas

    def query_table_in_schema(self, database_name, schema_name, page_no, page_size=100):
        """
        @函数说明：查询某个schema中的表
        返回值 table_list 不包含 database/schema 前缀
        """
        tables = DwsTable(DwsTableParam(user_name=self._usr, env_file=self._env_path,
                                        db_name=database_name, schema_name=schema_name,
                                        condition={"pageNo": page_no, "pageSize": page_size})).get_all_tables()

        ret_tables = []
        for table in tables:
            ret_tables.append(table.get('name').split('/').pop())

        return ret_tables

    def get_all_schemas(self, database_name):
        """
            功能描述：查询所有的schema
            参数：@usr_name：
            @env_path：
            @database_name： 数据库名称
            返回值：schema列表
        """
        page_no = 0
        page_size = 100
        total_schemas = []
        while True:
            schemas = self.query_schema_in_database(database_name, page_no, page_size)
            total_schemas += schemas
            if len(schemas) < page_size:
                break
            page_no += 1

        return total_schemas

